package com.yowasa.xiuxian.engine.message.battle;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.BattleEngine;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.entity.bo.battle.BattleContent;
import com.yowasa.xiuxian.entity.bo.user.UserBO;
import com.yowasa.xiuxian.entity.bo.user.UserBattle;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.XiuXianExtend;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.helper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.yowasa.xiuxian.util.ContentUtil.getIndex;


@CMD(name="/记忆战场")
public class LiftingHandler extends CmdMessageHandler {
    @Autowired
    private MessageHelper messageHelper;
    @Autowired
    private UserHelper userHelper;
    @Autowired
    private BattleEngine battleEngine;
    @Autowired
    private BattleHelper battleHelper;
    @Autowired
    private ExtendHelper extendHelper;
    @Autowired
    private BattleFieldHelper battleFieldHelper;
//开始，学习，商店，前往，突破，游历，个人信息，冒险家协会，地图，帮助
    public static final Logger logger = LoggerFactory.getLogger(LiftingHandler.class);

    //物速攻  物反甲  法血魔  法推
    //魔偶剑鬼   遗迹巨蛇  黯色空壳  洛蒂娅
    @Override
    public void execute(SendMessage message) {
        UserBO firstUser = userHelper.checkOpUserAll(message);

        List<String> params = getAllParam(message);//获取名称
        if (StringUtils.isEmpty(params.get(0))) {
            messageHelper.replyMys(message, "可以在后面追加 查看 排行榜 挑战 我的 测试 等二级指令进行后续操作");
            return;
        }
        if(firstUser.getStage() < 3){
            throw new HandlerException("参与记忆战场需要始明之青以上");
        }
        //获取当前层数
        XiuXianExtend byAccountId = extendHelper.getByAccountId(firstUser.getId());
        //获取本层怪物
        List<UserBO> userList = userHelper.getBattleFieldList(firstUser,byAccountId);
        if ("查看".equals(params.get(0))) {
            StringBuffer sb = new StringBuffer();
            //你当前处于记忆战场 xx 层 xx区
            //嚎哭,废土,禁忌,原罪,苦痛,红莲,无限
            ArrayList<String> list = Lists.newArrayList("原初","嚎哭","废土","禁忌","原罪","苦痛","红莲","无限");
            sb.append("你当前处于记忆战场").append(list.get(byAccountId.getBattleField())).append("层\n")
                    .append("\n本层存在怪物：").append(enemyMessage(userList));
            messageHelper.replyMys(message, sb.toString());

        }
        if ("排行榜".equals(params.get(0))) {
            if(params.size() <= 1){
                throw new HandlerException("正确指令为 /记忆战场 排行榜 层级名称 ，层级分为 嚎哭,废土,禁忌,原罪,苦痛,红莲,无限");
            }
            ArrayList<String> list = Lists.newArrayList("嚎哭","废土","禁忌","原罪","苦痛","红莲","无限");
            String s = params.get(1);
            int i = list.indexOf(s);
            if(i == -1){
                throw new HandlerException("不存在这样的层级");
            }
            String a = battleFieldHelper.rankList(i+1);
            messageHelper.replyMys(message, a);

        }
        if ("挑战".equals(params.get(0))) {
            if(params.size() <= 1){
                throw new HandlerException("正确指令为 /记忆战场 挑战 怪物名称 ，怪物名称支持模糊输入");
            }
            String secondName = params.get(1);

            UserBO secondUser = userList.stream().filter(e -> e.getName().contains(secondName)).findFirst().orElse(null);
            if(ObjectUtil.isNull(secondUser)){
                throw new HandlerException("输入的怪物名称有误");
            }
            //战斗
            BattleContent battle = battleEngine.battle(firstUser, secondUser);
            //本次造成伤害
            int i = battle.getSecond().getBattleInfo().getHp() - battle.getSecond().getBattleInfo().getChp();
            battleHelper.syncUserState(battle);
            StringBuffer msg = new StringBuffer();
            msg.append("你合计造成了" + i + "点伤害\n");
            try {
                int point = (i * 1000) / battle.getSecond().getBattleInfo().getHp();
                battleFieldHelper.insertOrUpdateDamage(firstUser, secondUser,point,byAccountId);
            }catch (Exception e){
                logger.info("存档出现错误：{}",e);
                logger.info("e.getMessage：{}",e.getMessage());
                throw new HandlerException("error");
            }

            int days = battleHelper.calCostTime(battle);
            userHelper.lockUser(battle.getFirst().getUserBO(),days/2,"正在挑战记忆战场");
            userHelper.saveUserInfo(battle.getFirst().getUserBO());
            msg.append(battle.getMsgLog().stream().collect(Collectors.joining("\n")));
            messageHelper.replyMys(message, msg.toString());
        }
        if ("我的".equals(params.get(0))) {
            StringBuffer sb = new StringBuffer();
            //你当前处于记忆战场 xx 层 xx区
            //嚎哭,废土,禁忌,原罪,苦痛,红莲,无限
            ArrayList<String> list = Lists.newArrayList("原初","嚎哭","废土","禁忌","原罪","苦痛","红莲","无限");
            sb.append("你当前处于记忆战场").append(list.get(byAccountId.getBattleField())).append("层\n");
            String a = battleFieldHelper.showMe(firstUser,byAccountId);
            sb.append(a);
            messageHelper.replyMys(message, sb.toString());

        }
        if ("测试".equals(params.get(0))) {

            try {
                UserBO newUser = ObjectUtil.clone(firstUser);
                StringBuffer msg = new StringBuffer();
                msg.append("木桩默认面板数据为自身面板，可通过输入参数调控，hp与mp默认无限，参数顺序为：\n物攻 法攻 物抗 法抗 速度 免疫\n指令示例：/记忆战场 测试 100 100 100 100 100 100 \n");
                //属性赋值
                newUser.setName("测试木桩");
                //hp atk spell def res sped imm
                newUser.getUserBattle().setHp(10000000);
                newUser.getUserBattle().setChp(10000000);
                newUser.getUserBattle().setMp(1000000);
                newUser.getUserBattle().setCmp(1000000);
                ArrayList<String> list = Lists.newArrayList("mp","atk", "spell", "def", "res", "spd", "imm");
                params.forEach(getIndex((e, index) -> {
                    Class<? extends UserBattle> aClass = newUser.getUserBattle().getClass();
                    if(index != 0){
                        Field field = null;
                        try {
                            field = aClass.getDeclaredField(list.get(index));
                        } catch (NoSuchFieldException ex) {
                            ex.printStackTrace();
                        }
                        field.setAccessible(true);
                        try {
                            field.set(newUser.getUserBattle(),Integer.parseInt(params.get(index)));
                        } catch (IllegalAccessException ex) {
                            ex.printStackTrace();
                        }
                    }
                }));

                newUser.setUserOriginBattle(newUser.getUserBattle());
                //清空战技
                newUser.getUserConfig().setBattleStrategyList(Sets.newHashSet());
                BattleContent battle = battleEngine.battle(firstUser, newUser);

                int i = 10000000 - battle.getSecond().getBattleInfo().getChp();
                msg.append("你造成的总伤害为："+i+"\n");
                msg.append(battle.getMsgLog().stream().collect(Collectors.joining("\n")));
                messageHelper.replyMys(message, msg.toString());
            }catch (Exception e){
                logger.info("木桩挑战error:{}",e);
                throw new HandlerException("出bug了QAQ");
            }
        }

    }


    private String enemyMessage(List<UserBO> userList) {
        if(userList.size() == 0){
            return "你还未踏入记忆战场，暂无怪物";
        }
        StringBuffer sb = new StringBuffer();
        userList.forEach(e -> {
            sb.append("\n怪物名称：").append(e.getName())
                    .append("\n怪物面板：\n").append(e.getUserBattle().getDesc())
                    .append("\n怪物战技：\n").append(String.join("\n", e.getUserConfig().getBattleStrategyList()));
            sb.append("\n\n");
        });
        return sb.toString();
    }

    public String desc(){
        return "记忆战场，苦痛升降机，沉沦在无尽的升降级中吧\n每层会有四个怪物，每个怪物计算1000分，可以溢出伤害进行超分\n\n升降级规则：无限没有升级区，嚎哭没有降级区\n" +
                "每层挑战者的前1/4会升级，后1/4会降级，每周进行一次结算";
    }


}
